local Msg = require("core.Msg")
local Lang = require("common.Lang")
local Broadcast = require("broadcast.Broadcast")
local ObjHuman = require("core.ObjHuman")

--local ExcelTaskConf = require("excel.Task")
--local ExcelFBountyConf = ExcelTaskConf.FamilyBountyTask


local TaskHelp = require("task.TaskHelp")
local TaskAction = require("task.TaskAction")
local TaskHandler = require("task.HandlerL")
local TaskDefine = require("task.Define")
local ItemDefine = require("bag.ItemDefine")

local BountyLogic = require("task.BountyLogic")
local HtmlUtil = require("common.HtmlUtil")


COOL_DOWN_TIME = 600		-- 冷却时间
MAX_CAN_DO_TIME = 10		-- 每日可接个数
MAX_CAN_OFFER_TIME = 5		-- 发布任务可提供领取次数
FREE_REFRESH_TIME = 2		-- 每天免费刷新次数

-- 设置任务节点信息
function setTaskNode(taskNode, human, offerUuid, taskData)
	local taskConfig = ExcelFBountyConf[taskData.taskID]	-- 任务配置信息
	if not taskConfig then
		assert(nil, taskID)
	end
	-- 任务基础信息
	taskNode.taskID = taskData.taskID
	taskNode.taskName = taskConfig.name
	if taskConfig.where ~= "" then
		if not taskConfig.taskName then
			taskConfig.taskName = string.format("%s%s%s%s",taskConfig.name , "【" , taskConfig.where ,"】")
		end
		taskNode.taskName = taskConfig.taskName
	end
	taskNode.color = taskConfig.color
	taskNode.icon = tostring(taskConfig.icon)
	
	-- 任务对象
	TaskAction.setTaskObj(taskNode, human, taskData.taskID, taskConfig)
	
	-- 任务奖励
	local exp, worldExpAdd = TaskHelp.getRewardExp(taskConfig, human)
	taskNode.rewardExp = exp + worldExpAdd
	taskNode.familyContribution = TaskHelp.getRewardFamilyContribution(taskConfig, human)
	taskNode.familyMoney = TaskHelp.getRewardFamilyExp(taskConfig, human)
	
	taskNode.offerUuid = offerUuid
	taskNode.offerName = taskData.offerName or ""
	taskNode.doCnt = taskData.doCnt
	taskNode.maxCnt = MAX_CAN_OFFER_TIME
end


-- 初始化信息
function initFamilyBounty(human)
	human.db.familyBounty = {doCnt = 0, getLastTime=nil, offerName=nil, freeTime = 0, refreshTime = 0}
	refreshTask(human)
end

local function getCoolDownTime(human)
	if not human.db.familyBounty then
		return 0
	end
	if not human.db.familyBounty.getLastTime then
		return 0	
	end
	if BibleLogic.isBibleBuy(human) == true then
		return 0
	end
	
	local res = human.db.familyBounty.getLastTime + COOL_DOWN_TIME - os.time()
	if res < 0 then
		res = 0
	end
	return res
end

local function getFamilyBountyDoCnt(family, offerUuid)
	if family.familyBounty and family.familyBounty[offerUuid] then
		return family.familyBounty[offerUuid].doCnt
	end
	return 0
end

local function checkIsAccept(family, acceptUuid, offerUuid)
	if family.familyBounty[offerUuid].list and family.familyBounty[offerUuid].list[acceptUuid] then
		return true
	end
end

function sendFamilyBountyList(human)
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ERR)
		return 
	end	
	ObjHuman.updateDaily(human)
	
	local msgRet = Msg.gc.GC_FAMILY_BOUNTY_LIST
	msgRet.list[0] = 0
	msgRet.nextTimeLeft = getCoolDownTime(human)
	msgRet.maxTimes = MAX_CAN_DO_TIME
	msgRet.doTimes = human.db.familyBounty and human.db.familyBounty.doCnt or 0
	
	if family.familyBounty then
		for uuid, data in pairs(family.familyBounty) do
			local getCnt = getFamilyBountyDoCnt(family, uuid)
			if getCnt < MAX_CAN_OFFER_TIME and checkIsAccept(family, human.db._id, uuid) ~= true 
				and data.taskID > 0 then
				msgRet.list[0] = msgRet.list[0] + 1
				setTaskNode(msgRet.list[msgRet.list[0]], human, uuid, data)	
			end		
		end
	end
	--Msg.trace(msgRet)
	Msg.send(msgRet, human.fd)
end

-- 刷新任务
BOUNTY_COLOR_WEIGHT = {20,37,39,3,1}		-- 颜色权重
local canDoList = {}
local canDoListWeight = {}
function refreshTask(human)
	for k in pairs(canDoList) do
		canDoList[k] = nil
	end
	for k in pairs(canDoListWeight) do
		canDoListWeight[k] = nil
	end
	local isUp = nil
	-- 第十次花费刷新以后必定出紫色
	if human.db.familyBounty.refreshTime and human.db.familyBounty.refreshTime == 10 then
		isUp = true
	end
	local weightSum = 0
	local len = 0
	for id, conf in pairs(ExcelFBountyConf) do
		if conf.level_min <= human.db.lv and conf.level_max >= human.db.lv then
			local color = conf.color
			len = len + 1
			canDoList[len] = id
			if isUp and color < 4 then
				canDoListWeight[len] = weightSum + 0
			else
				canDoListWeight[len] = weightSum + BOUNTY_COLOR_WEIGHT[color]
			end
			weightSum = canDoListWeight[len]
		end
	end	
	
	if weightSum < 1 then
		human.db.familyBounty.taskID = 0
		return
	end
	
	local randNum = math.random(1, weightSum) 
	for i = 1, len do
		if canDoListWeight[i] >= randNum then
			human.db.familyBounty.taskID = canDoList[i]
			break
		end
	end
end



-- 个人任务信息
function sendFamilyBountyOffer(human)		
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ERR)
		return 
	end		
	
	ObjHuman.updateDaily(human)
	
	local msgRet = Msg.gc.GC_FAMILY_BOUNTY_OFFER
	if not human.db.familyBounty then
		initFamilyBounty(human)
	end
	
	-- 等级未够时，可能刷新过军团任务信息
	if not human.db.familyBounty.taskID or human.db.familyBounty.taskID <= 0 then
		refreshTask(human)
	end
	
	if human.db.familyBounty.taskID	<= 0 then
		return
	end
	
	local taskID = human.db.familyBounty.taskID		-- 等级够时，不可能为空
	local conf = ExcelFBountyConf[taskID]
	TaskHelp.setTaskNode(msgRet.myBounty, taskID, human)
	msgRet.myBounty.taskCanFly = 0
	msgRet.icon = conf.icon
	msgRet.maxCnt = -1
	msgRet.doCnt = 0
	msgRet.freeRefreshTime = FREE_REFRESH_TIME - (human.db.familyBounty.freeTime or 0)
	if msgRet.freeRefreshTime < 0 then
		msgRet.freeRefreshTime = 0
	end
	
	if family.familyBounty then
		if family.familyBounty[human.db._id] then
			msgRet.maxCnt = MAX_CAN_OFFER_TIME
			msgRet.doCnt = family.familyBounty[human.db._id].doCnt
		elseif human.db.familyBounty.isOffer then
			msgRet.maxCnt = MAX_CAN_OFFER_TIME
			msgRet.doCnt = MAX_CAN_OFFER_TIME
		end		
	end
	--Msg.trace(msgRet)
	Msg.send(msgRet, human.fd)
end

-- 发布任务
function offerTask(human)
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ERR)
		return 
	end	
	
	ObjHuman.updateDaily(human)
	
	if not human.db.familyBounty then
		initFamilyBounty(human)
	end
	
	if not human.db.familyBounty.taskID or human.db.familyBounty.taskID <= 0 then
		refreshTask(human)
	end
	
	-- 不能重复发布
	if human.db.familyBounty.isOffer then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_OFFER_ERR_HAD)
		return
	end
	
	if not family.familyBounty then
		family.familyBounty = {}
	end	
	
	local taskID = human.db.familyBounty.taskID
	
	family.familyBounty[human.db._id] = {taskID=taskID, offerName = human.db.name, doCnt = 0}	
	human.db.familyBounty.isOffer = true
	
	
	sendFamilyBountyList(human)
	sendFamilyBountyOffer(human)
	
	local fds = FamilyManager.getOnlineFds(family)	
	Broadcast.sendBroadcastFDs(fds, Lang.FAMILY, string.format(Lang.TASK_FBOUNTY_OFFER_OK, human.db.name) .. HtmlUtil.fontOpenPanelLink(56, Lang.TASK_FBOUNTY_OFFER_OK_LINK))
end

-- 刷新任务
function doTaskRefresh(human)
	-- 无军团，不能刷新
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ERR)
		return 
	end		
	
	ObjHuman.updateDaily(human)
	
	if not human.db.familyBounty then
		initFamilyBounty(human)
	end
	
	-- 已发布，不能刷新
	if human.db.familyBounty.isOffer then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_REFRESH_ERR_OFFER)
		return
	end
	
	local rmbNeed = 10
	human.db.familyBounty.freeTime = human.db.familyBounty.freeTime or 0
	if FREE_REFRESH_TIME > human.db.familyBounty.freeTime then
		human.db.familyBounty.freeTime = human.db.familyBounty.freeTime + 1
		rmbNeed = 0
	end
	
	if human.db.yuanbao < rmbNeed and human.db.liquan < rmbNeed then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_REFRESH_ERR_RMB)
		return 
	end
	
	if rmbNeed > 0 then
		human.db.familyBounty.refreshTime = (human.db.familyBounty.refreshTime or 0) + 1
	end
		
	local yb, lq = 0, 0
	if rmbNeed > 0 then
		yb, lq = BountyLogic.useLiquanFirst(human, rmbNeed, "refresh_family_bounty")
	end
	if yb > 0 then
		Broadcast.sendBroadcast(human, Lang.DOWN, string.format(Lang.TASK_FBOUNTY_REFRESH_OK_YUANBAO, yb))
	elseif lq> 0 then
		Broadcast.sendBroadcast(human, Lang.DOWN, string.format(Lang.TASK_FBOUNTY_REFRESH_OK_LIQUAN, lq))
	else
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_REFRESH_OK)
	end
	
	refreshTask(human)
	sendFamilyBountyOffer(human)	
end

local function addFamilyBountyAccept(family, acceptUuid, offerUuid)
	family.familyBounty[offerUuid].doCnt = family.familyBounty[offerUuid].doCnt + 1
	family.familyBounty[offerUuid].list = family.familyBounty[offerUuid].list or {}
	family.familyBounty[offerUuid].list[acceptUuid] = true
end

-- 当前已接军团任务个数
function getAcceptCnt(human)
	local doingTasksLen, doingTasks = TaskHelp.getDoing(human)
	local cnt = 0
	
	for i = 1, doingTasksLen do
		local taskConfig = TaskHelp.getTaskConfig(doingTasks[i]) -- 任务配置信息
		
		if taskConfig and taskConfig.mainType == TaskDefine.TASK_TYPE_1_FAMILYBOUNTY then
			cnt = cnt + 1
		end
	end
	
	return cnt
end


-- 接受任务
function doTaskAccept(human, offerUuid)
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ERR)
		return 
	end	
	
	ObjHuman.updateDaily(human)
		
	if not human.db.familyBounty then
		initFamilyBounty(human)
	end
	
	if not family.familyBounty or not family.familyBounty[offerUuid] then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ACCEPT_ERR_ID)
		return 
	end	
	
	-- 自己的任务不能领取	
	if offerUuid == human.db._id then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ACCEPT_ERR_SELF)
		return
	end
	
	-- 冷却中
	local res = getCoolDownTime(human)
	if res > 0 then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ACCEPT_ERR_COOL)
		return
	end
	
	-- 已接过
	if checkIsAccept(family,  human.db._id, offerUuid) == true then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ACCEPT_ERR_HAD)
		return		
	end
	
	-- 接取次数上限
	if getFamilyBountyDoCnt(family, offerUuid) >= MAX_CAN_OFFER_TIME then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_ACCEPT_ERR_CNT)
		return	
	end
	
	-- 每次只能接受一个军团任务
	if getAcceptCnt(human) > 0 then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_REFRESH_ERR_ONE)
		return		
	end
	
	if human.db.familyBounty.doCnt >= MAX_CAN_DO_TIME then
		Broadcast.sendBroadcast(human, Lang.DOWN, Lang.TASK_FBOUNTY_REFRESH_ERR_DAY)
		return			
	end
	
	local taskID = family.familyBounty[offerUuid].taskID
	if TaskHandler.CG_TASK_ACCEPT(human, {taskID=taskID}) then
		TaskHelp.refreshDoing(human)
		
		human.db.familyBounty.doCnt = human.db.familyBounty.doCnt + 1
		human.db.familyBounty.getLastTime = os.time()
		human.db.familyBounty.offerUuid = offerUuid
		
		addFamilyBountyAccept(family, human.db._id, offerUuid)		
		
		local msgRet = Msg.gc.GC_FAMILY_BOUNTY_ACCEPT
		msgRet.offerUuid = offerUuid
		msgRet.nextTimeLeft = getCoolDownTime(human)
		msgRet.doTimes = human.db.familyBounty.doCnt
		Msg.send(msgRet, human.fd)				
	end
end

local fields = {lv = 1}

function sendReward2Offer(human, taskConfig)
	if not human.db.familyBounty or not human.db.familyBounty.offerUuid then
		return
	end
	
	local uuid = human.db.familyBounty.offerUuid
	
	local oHuman = ObjHuman.onlineUuid[uuid]	
	if not oHuman then
		oHuman = {}
		oHuman.db = RoleDBLogic.getDb(uuid, fields)	
	end
	
	local exp = TaskHelp.getRewardExp(taskConfig, oHuman)
	local familyContribution = TaskHelp.getRewardFamilyContribution(taskConfig, oHuman)	
	local grids = {}
	
	if exp > 0 then
		grids[#grids + 1] = RefineUtil.getCacheGrid(ItemDefine.ITEM_ID_JINGYAN)
		grids[#grids].cnt = exp
	end
	
	if familyContribution > 0 then
		grids[#grids + 1] = RefineUtil.getCacheGrid(ItemDefine.ITEM_ID_FAMILY_CONTRIBUTION)
		grids[#grids].cnt = familyContribution
	end
	MailHandler.addSystemMessage(uuid,Lang.TASK_FBOUNTY_MAIL_TITLE, string.format(Lang.TASK_FBOUNTY_MAIL_CONTENT, human.db.name),grids)
end

function refresh(human, os_time)
	local offerUuid = human.db.familyBounty and human.db.familyBounty.offerUuid
	initFamilyBounty(human)
	human.db.familyBounty.offerUuid = offerUuid
	
	local family = FamilyManager.findByUuid(human.db.familyUuid)
	if not family then	-- 无军团
		return 
	end	
	FamilyManager.updateDaily(family, os_time)
end







